/*
 * Sched.cpp
 *
 *  Created on: 05-08-2011
 *      Author: cristian
 */

#include "Sched.h"

Sched::Sched() {
	this->logger = new Logger();

}

void Sched::createWorker(std::string nombre, std::string descripcion) {

	Worker* w = new Worker(nombre, descripcion);
	workers.push_back(w);

}

Sched::~Sched() {

	this->workers.clear();
	delete logger;

}

void Sched::trace() {
	list<Worker*>::iterator pos;
	pos = this->workers.begin();

	while (pos != workers.end()) {
		((*pos))->trace();
		pos++;
	}
}

void Sched::stopWorkers() {

#ifdef TRACE
	HAL_TRACE(this->logger, " Stop Workers");
#endif

	list<Worker*>::iterator pos;
	pos = this->workers.begin();

	while (pos != workers.end()) {
		(*pos)->stop();
		pos++;
	}
}

void Sched::runWorkers() {

#ifdef TRACE
	HAL_TRACE(this->logger, " Run Workers");
#endif

	list<Worker*>::iterator pos;
	pos = this->workers.begin();

	while (pos != workers.end()) {

		int rc = pthread_create((*pos)->getThread(), NULL, Worker::start,
				(*pos));

		if (rc) {
			/*
			 * @TODO Log para los errores.
			 */
		}
		pos++;
	}
}

void Sched::printStatusWorkers() {

#ifdef TRACE
	HAL_TRACE(this->logger, " Status Workers ...");
#endif

	list<Worker*>::iterator pos;
	pos = this->workers.begin();

	while (pos != workers.end()) {
#ifdef TRACE
		HAL_TRACE(
				this->logger,
				"Worker : %s  is Run: %i", (*pos)->getNombre().c_str(), (*pos)->getRun());
		(*pos)->trace();
#endif
		pos++;
	}

}

void Sched::stopWorker(int posicion) {
	int i = 1;

	list<Worker*>::iterator pos;
	pos = this->workers.begin();

	while (pos != workers.end()) {
		if (i == posicion) {
			(*pos)->stop();
			return;
		}
		pos++;
	}
}

void Sched::createWorkerAndRun(std::string nombre, std::string descripcion) {

	Worker* w = new Worker(nombre, descripcion);
	workers.push_front(w);

	list<Worker*>::iterator pos;
	pos = this->workers.begin();

	(*pos)->trace();

	int rc = pthread_create((*pos)->getThread(), (*pos)->getAttr(), Worker::start, (*pos));

	if (rc) {
		/*
		 * @TODO Log para los errores.
		 */
	}

}

void Sched::addObserverToWorkers(Observer *observer) {

	list<Worker*>::iterator pos;
	pos = this->workers.begin();

	while (pos != workers.end()) {

#ifdef TRACE
		HAL_TRACE(logger,
				"Observer Agregado al worker %s", (*pos)->getNombre().c_str());
#endif

		(*pos)->addObserver(observer);
		pos++;
	}
}

void Sched::printSize()
{

	#ifdef TRACE
		HAL_TRACE(logger, "Cantidad de Workers : %i" , this->workers.size());
	#endif
}


